package com.micro.platform.starter.config.loadbalance.dubbo;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.RouterFactory;
import org.apache.dubbo.rpc.cluster.router.AbstractRouter;

import java.util.List;


/**
 * @com.alibaba.cloud.dubbo.service.MetadataServiceRevisionRouterFactory
 */
@Activate(order = 400)
public class LocalRouterFactory implements RouterFactory {

    public static final String NAME = "lcoal";

    public static final String LCOAL_FIELD_KEY = "version";

    private volatile Router router;

    @Override
    public Router getRouter(URL url) {
        if (router != null) {
            return router;
        }
        synchronized (this) {
            if (router == null) {
                router = createRouter(url);
            }
        }
        return router;
    }

    private Router createRouter(URL url) {
        return new AbstractRouter() {
            @Override
            public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
                return invokers;
//                System.out.println(JSON.toJSONString(url));
//                System.out.println(JSON.toJSONString(invocation));
//                System.out.println(JSON.toJSONString(invokers));
//                if (CollectionUtils.isEmpty(invokers)) {
//                    return invokers;
//                }
//
//                String field = invocation.getAttachment(LCOAL_FIELD_KEY);
//
//                if (StringUtils.isEmpty(field)) {
//                    return invokers;
//                }
//
//                List<Invoker<T>> filterInvokers = invokers.stream()
//                        .filter(invoker -> StringUtils.equals(field, invoker.getUrl().getParameter(LCOAL_FIELD_KEY)))
//                        .collect(Collectors.toList());
//                return filterInvokers;
            }
        };
    }
}
